<template>
    <Category :scene="scene"></Category>

    <el-card shadow="hover" :body-style="{ padding: '20px' }" style="margin-top:10px">
        <div v-show="scene==0">
            <el-button type="primary" size="default" :icon="Plus" style="margin-bottom:10px" @click="addAttr"
                :disabled="categoryStore.c3Id ? false : true">添加属性</el-button>

            <el-table border stripe :data="attrList">
                <el-table-column label="序号" width="70px" type="index" align="center">
                </el-table-column>
                <el-table-column label="属性名称" width="160px" prop="attrName">
                </el-table-column>
                <el-table-column label="属性值列表">
                    <template #="{row,$index}">
                        <el-tag type="danger" style="margin:0px,5px" v-for="(attrVal,index) in row.attrValueList"
                            :key="attrVal.id">{{attrVal.valueName}}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="160px">
                    <template #="{row,$index}">
                        <el-button type="primary" size="small" :icon="Edit" @click="updateAttr(row)"></el-button>
                        <el-button type="danger" size="small" :icon="Delete" @click="deleteAttr(row)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div v-show="scene==1">
            <el-form :inline="true">
                <el-form-item label="属性名">
                    <el-input placeholder="请输入属性名字" v-model="attrParams.attrName"></el-input>
                </el-form-item>
            </el-form>

            <el-button type="primary" size="default" :icon="Plus"
                :disabled="attrParams.attrName.length > 0 ? false : true" @click="addAttrValue(row)">添加属性值</el-button>
            <el-button size="default" @click="cancel">取消</el-button>


            <el-table border stripe style="margin:20px 0px" :data="attrParams.attrValueList">
                <el-table-column label="序号" width="70px" type="index" align="center">
                </el-table-column>
                <el-table-column label="属性值名称">
                    <template #="{row,$index}">
                        <el-input v-model="row.valueName" size="normal" clearable v-if="row.flag" placeholder="请输入属性值"
                            :ref="(vc)=>(inputAttr[$index] = vc)" @blur="toLook(row,$index)"></el-input>
                        <div v-else @click="toEdit(row,$index)">{{row.valueName}}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #="{row,$index}">
                        <el-button type="danger" size="small" :icon="Delete"
                            @click="attrParams.attrValueList.splice($index,1)"></el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-button type="primary" size="default" @click="save"
                :disabled="attrParams.attrValueList.length>0 ? false:true">保存</el-button>
            <el-button size="default" @click="cancel">取消</el-button>
        </div>
    </el-card>
</template>

<script setup lang="ts">
//引入element-plus提供的图标库组件
import {
    Check,
    Delete,
    Edit,
    Message,
    Search,
    Star,
    Plus
} from '@element-plus/icons-vue'

import { ElMessage } from 'element-plus'

//引入组合式APIwatch
import { ref, watch, reactive, nextTick,onMounted} from 'vue';
//引入请求函数
import { reqAttrList, reqAddUpdateAttr, reqDeleteAttr } from '@/api/product/attr/attr';
//引入分类的仓库
import useCategoryStore from '@/stores/category';
let categoryStore = useCategoryStore();
//储存数据
let attrList = ref([]);
//定义数组ref类型数据，将来储存el-input组件的实例
let inputAttr = ref([]);
//切换添加页面
let scene = ref<number>(0);
//监听三级分类的ID变化，发送请求
watch(
    () => categoryStore.c3Id,
    () => {
        //判断三级分类ID，拿数据
        if (categoryStore.c3Id == '') return;
        //获取平台属性方法
        getAttrList();
    }
);
//获取商品属性的方法
const getAttrList = async () => {
    let result = await reqAttrList(
        categoryStore.c1Id,
        categoryStore.c2Id,
        categoryStore.c3Id,
    );
    //存储平台数据
    attrList.value = result;
};
//添加或修改数据请求返回的参数
let attrParams = reactive({
    attrName: "",//名称
    attrValueList: [//每条数据的内容
        // {
        //   "attrId": 0,
        //   "id": 0,
        //   "valueName": ""
        // }
    ],
    categoryId: '',//点击某个分类的ID
    categoryLevel: 3,//固定三级分类ID
})


//添加属性按钮
const addAttr = () => {
    scene.value = 1;
    Object.assign(attrParams, {
        attrName: "",//名称
        attrValueList: [//每条数据的内容
            // {
            //   "attrId": 0,
            //   "id": 0,
            //   "valueName": ""
            // }
        ],
        categoryId: categoryStore.c3Id,//点击某个分类的ID
        categoryLevel: 3,//固定三级分类ID
    })
};

//点击取消按钮的事件回调
const cancel = () => {
    scene.value = 0;
};

//点击添加属性值的回调函数
const addAttrValue = () => {
    attrParams.attrValueList.push({
        valueName: '',
        flag: true
    });
    nextTick(() => {
        inputAttr.value[attrParams.attrValueList.length - 1].focus();
    })
};
//div失去焦点以后切换
const toLook = (row, $index) => {
    //属性值一些非法情况需要判断
    //属性值为空
    if (row.valueName.trim() == '') {
        ElMessage({
            type: 'warning',
            message: '输入的内容不能为空哦'
        });
        //属性值数组把当前非法属性对象消除
        attrParams.attrValueList.splice($index, 1);
        //代码后面不能执行
        return
    }


    //属性值重名
    let repeat = attrParams.attrValueList.find((item) => {
        //先把数组中自身数据扣除
        if (row != item) {
            return row.valueName === item.valueName;
        }
    })

    //如果重复出现
    if (repeat) {
        ElMessage({
            type: 'warning',
            message: `${repeat.valueName}重复啦！`
        });
        //属性值把当前非法属性值删除
        attrParams.attrValueList.splice($index, 1);
        return;
    }
    row.flag = false
};
//div点击切换成编辑模式
const toEdit = (row, $index) => {
    row.flag = true;
    //点击div切换显示el-input，需要聚焦
    nextTick(() => {
        inputAttr.value[$index].focus();
    });
};

//点击保存按钮的事件回调
const save = async () => {
    //整理参数：属性值的数组flag属性不需要
    attrParams.attrValueList.forEach((item) => {
        if (item.hasOwnProperty('flag')) {
            //删除某一个属性
            delete item.flag;
        }
    });

    try {
        //添加属性成功
        await reqAddUpdateAttr(attrParams);
        //切换场景
        scene.value = 0;
        ElMessage({
            type: 'success',
            message: attrParams.id ? '修改成功' : '添加成功'
        });
        //获取最新数据
        getAttrList();
    } catch (error) {
        ElMessage({
            type: 'error',
            message: attrParams.id ? '修改失败' : '添加失败'
        })
    }


};
//修改按钮逻辑
const updateAttr = (row: any) => {
    scene.value = 1;
    nextTick(() => {
        Object.assign(attrParams,JSON.parse(JSON.stringify(row)))
    })
};
//删除按钮逻辑
const deleteAttr = async (row) => {
    try {
        await reqDeleteAttr(row.id);
        ElMessage({
            type: 'success',
            message: `删除${row.attrName}成功`,
            duration: 500,//约束提示信息的事件
        })
        getAttrList();
    } catch (error) {
        ElMessage({
            type: 'danger',
            message: `删除${row.attrName}失败`,
        })
    }
};
onMounted(()=>{
    categoryStore.c1Id = '',
    categoryStore.c2Id = '',
    categoryStore.c3Id = '',
    categoryStore.c1List = [],
    categoryStore.c2List = [],
    categoryStore.c3List = []
})
</script>

<style scoped>

</style>